package cn.ecnu.controller;

import cn.ecnu.common.IM.TLSSigAPIv2;
import cn.ecnu.common.utils.R;
import cn.ecnu.mapper.UserMapper;
import cn.ecnu.mapper.VisitorMapper;
import cn.ecnu.pojo.User;
import cn.ecnu.pojo.Visitor;
import cn.ecnu.service.AccountService;
import cn.ecnu.vo.fromFront.LoginForm;
import cn.ecnu.vo.fromFront.MiniLoginForm;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.ecnu.common.constant.BusinessConstant.SDK_APP_ID;
import static cn.ecnu.common.constant.BusinessConstant.SDK_KEY;

@RestController
@RequestMapping("/account")
public class AccountController {

    @Resource
    private AccountService accountService;

    @Resource
    private VisitorMapper visitorMapper;

    @Resource
    private UserMapper userMapper;

    private TLSSigAPIv2 helper = new TLSSigAPIv2(SDK_APP_ID, SDK_KEY);

    @PostMapping("/webLogin")
    public R webLogin(@RequestBody LoginForm vo) {
        Map<String, Object> map = accountService.webLogin(vo);
        return R.ok().put("data", map);
    }

    @PostMapping("/logout/{userId}")
    public R logout(@PathVariable Integer userId) {
        accountService.logout(userId);
        return R.ok();
    }

    @PostMapping("/miniLogin")
    public R miniLogin(@RequestBody MiniLoginForm vo) {
        try {

            String openid = accountService.getOpenId(vo.getCode());

            //查看这个openid是否存在于数据库中
            List<Visitor> visitors = visitorMapper.getAllVisitors();
            for (Visitor visitor : visitors) {
                //如果是老用户，更新昵称和头像的信息，返回用户的id给前端
                if (visitor.getOpenId().equals(openid)) {
                    User user = userMapper.getUserById(visitor.getVisitorId());
                    user.setUserNickname(vo.getNickname());
                    user.setUserAvatar(vo.getAvatarUrl());
                    userMapper.updateUser(user);
                    //如果是被禁用的，无法登录
                    if (visitor.getIsBanned().equals("1")) {
                        return R.error(400, "您的账户已被禁用");
                    }
                    visitor.setLastLoginTime(new Date());
                    visitorMapper.updateVisitor(visitor);
                    HashMap<Object, Object> res = new HashMap<>();
                    res.put("id", user.getUserId());
                    return R.ok().put("data", res);
                }
            }

            //如果是新用户，加入数据库

            //user
            User newUser = new User();
            newUser.setUserAvatar(vo.getAvatarUrl());
            newUser.setUserNickname(vo.getNickname());
            newUser.setRole(0);
            userMapper.insertUser(newUser);

            //visitor
            Visitor newVisitor = new Visitor();
            newVisitor.setVisitorId(newUser.getUserId());
            newVisitor.setOpenId(openid);
            newVisitor.setLastLoginTime(new Date());
            newVisitor.setIsBanned("0");
            visitorMapper.insertVisitor(newVisitor);

            HashMap<Object, Object> res = new HashMap<>();
            res.put("id", newUser.getUserId());

            return R.ok().put("data", res);

        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @GetMapping("/getUserSig/{id}")
    public R getUserSig(@PathVariable("id") Integer id) {
        try {
            String userSig = helper.genUserSig(String.valueOf(id), 86400);
            HashMap<Object, Object> res = new HashMap<>();
            res.put("userSig", userSig);
            return R.ok().put("data", res);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

}
